import Dialog from "../../../../component/vant/dialog/dialog";

let app = getApp()
var esc = require("../../../utils/esc.js")
const util = require('../../../../utils/util.js')
const print = require('../../../utils/print.js')

Page({

    /**
     * 页面的初始数据
     */
    data: {
        order: {},
        customerBillStat: {},
        details: [],
        dynamicCargoData: [{
            "cargoNo": "",
            "wholesalePrice": "",
            "skuInfoList": []
        }],
        orderId: 0,
        // 打印所配置
        // 循环次数
        looptime: 0,
        // 当前次数
        currentTime: 1,
        // 最后循环次数的字节数
        lastData: 0,
        // 循环一次打印的字节数
        oneTimeData: 0,
        // 一次打印字节数list
        buffSize: [],
        // 一次打印字节数list下标值
        buffIndex: 0, //发送字节数下标
        // 打印分数选择list
        printNum: [],
        // 打印份数list下标值
        printNumIndex: 0,
        // 打印份数值
        printerNum: 1,
        // 当前打印份数
        currentPrint: 1,
        // 防止重复点击打印按钮
        isReceiptSend: false,
        // 防止重复点击查询按钮
        isQuery: false,
        imageSrc: '../../imags/wechat.png',
        jpgSrc: '../../imags/flower2.jpg',
        canvasWidth: 100,
        canvasHeight: 100,
        jpgWidth: 200,
        jpgHeight: 200,

        //action-sheet
        actions: [],
        actions_status_0: [
            {name: '新增', type: "add"},
            {name: '复制', type: "copy"},
            {name: '修改', type: "edit"},
            {name: '撤销', type: "cancel"},
            {name: '工作台', type: "homepage"},
        ],
        actions_status_1: [
            {name: '新增', type: "add"},
            {name: '复制', type: "copy"},
            {name: '修改', type: "edit"},
            {name: '撤销', type: "cancel"},
            {name: '工作台', type: "homepage"},
        ],
        actions_status_2: [
            {name: '新增', type: "add"},
            {name: '复制', type: "copy"},
            {name: '撤销', type: "cancel"},
            {name: '工作台', type: "homepage"},
        ],
        actions_status_9: [
            {name: '新增', type: "add"},
            {name: '复制', type: "copy"},
            {name: '工作台', type: "homepage"},
        ],
        actionSheetShow: false,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let orderId = null
        if (options.orderId) {
            orderId = options.orderId
        } else {
            let obj = wx.getLaunchOptionsSync()
            if (obj) {
                orderId = obj.query.orderId
            }
        }
        this.data.orderId = orderId
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        var list = []
        var numList = []
        var j = 0
        for (var i = 20; i < 200; i += 10) {
            list[j] = i;
            j++
        }
        for (var i = 1; i < 10; i++) {
            numList[i - 1] = i
        }
        this.setData({
            buffSize: list,
            oneTimeData: list[0],
            printNum: numList,
            printerNum: numList[0]
        })
    },
    onShow: function () {
        let orderId = this.data.orderId
        if (orderId > 0) {
            this.queryData(orderId)
        }
    },
    moreFun: function () {
        let status = this.data.order.status
        if (status == 0) {
            this.setData({
                actions: this.data.actions_status_0
            })
        } else if (status == 1) {
            this.setData({
                actions: this.data.actions_status_1
            })
        } else if (status == 2) {
            this.setData({
                actions: this.data.actions_status_2
            })
        } else if (status == 9) {
            this.setData({
                actions: this.data.actions_status_9
            })
        } else {
            this.setData({
                actions: this.data.actions_status_0
            })
        }
        this.setData({
            actionSheetShow: true
        })
    },
    actionSelect: function (e) {
        let type = e.detail.type
        if (type == 'add') {
            wx.redirectTo({
                url: "/pages/order/add/index"
            })
        } else if (type == 'edit') {
            wx.redirectTo({
                url: "/pages/order/edit/orderEdit?orderId=" + this.data.orderId
            })
        } else if (type == 'copy') {
            wx.redirectTo({
                url: "/pages/order/add/index?copyOrderId=" + this.data.orderId
            })
        } else if (type == 'cancel') {
            Dialog.confirm({
                title: '是否确认撤销该单据？',
                message: '撤销后将撤销相应的库存、账目，且撤销后不可恢复',
            })
                .then(() => {
                    this.handleOrderCancel()
                })
                .catch(() => {
                    console.log("concel")
                });
        } else if (type == 'homepage') {
            wx.switchTab({
                url: "/pages/index/index"
            })
        }
    },
    actionCancel() {
        this.setData({actionSheetShow: false});
    },
    actionClose: function () {
        this.setData({actionSheetShow: false});
    },
    queryData: function (orderId) {
        let _this = this
        this.setData({
            spinShow: true
        });
        app.formGet('/app/order/getOrderDetail?orderId=' + orderId, null).then(res => {
            _this.setData({
                spinShow: false
            });
            wx.stopPullDownRefresh()
            if (res.code === 0) {
                _this.setData({
                    order: res.data.order,
                    customerName: res.data.order.receiver + "(" + res.data.order.rarea + ")",
                    customerBillStat: res.data.customerBillStat,
                    dynamicCargoData: res.data.details
                });
            } else {
                app.message(res.message, 'error')
            }
        }).catch(e => {
            _this.setData({
                spinShow: false
            });
            app.message(e, 'error')
        })
    },
    viewOutStoreBill: function () {
        wx.navigateTo({
            url: "/pages/outstore/index/outStoreIndex?orderId=" + this.data.orderId
        })
    },
    handleOrderConfirm() {
        wx.navigateTo({
            url: "/pages/order/confirm/confirm?orderId=" + this.data.orderId
        })
    },
    handleOrderPart: function () {
        wx.navigateTo({
            url: "/pages/order/out-store/index?orderId=" + this.data.orderId
        })
    },
    handleOrderFinish: function () {
        let _this = this
        Dialog.confirm({
            title: '温馨提示',
            message: '销售单确定要全部出库吗？',
        })
            .then(() => {
                let data = {}
                data.id = this.data.orderId
                _this.setData({
                    spinShow: false
                });
                app.formPost('/app/order/completeOutStore', data).then(res => {
                    _this.setData({
                        spinShow: false
                    });
                    wx.stopPullDownRefresh()
                    if (res.code === 0) {
                        app.toast(res.message, 'success')
                        setTimeout(function () {
                            wx.switchTab({
                                url: '/pages/order/index-all/index-all'
                            })
                        }, 2000)
                    } else {
                        app.message(res.message, 'error')
                    }
                }).catch(e => {
                    _this.setData({
                        spinShow: false
                    });
                    app.message(e, 'error')
                })
            })
            .catch(() => {
                console.log("concel")
                // on cancel
            });
    },
    handleOrderCancel() {
        let _this = this
        let data = {}
        data.id = this.data.orderId
        app.formPost('/app/order/cancel', data).then(res => {
            _this.setData({
                spinShow: false
            });
            wx.stopPullDownRefresh()
            if (res.code === 0) {
                app.message(res.message, 'success')
                setTimeout(function () {
                    wx.switchTab({
                        url: '/pages/order/index-all/index-all'
                    })
                }, 2000)
            } else {
                app.message(res.message, 'error')
            }
        }).catch(e => {
            _this.setData({
                spinShow: false
            });
            app.message(e, 'error')
        })
    },
    orderPrintStatusUpdate(status) {
        let data = {}
        data.id = this.data.orderId
        data.status = status
        app.formPost('/app/order/print', data).then(res => {
            if (res.code === 0) {
                app.message(res.message, 'success')
            } else {
                app.message(res.message, 'error')
            }
        }).catch(e => {
            app.message(e, 'error')
        })
    },
    freeShare: function () {
        wx.navigateToMiniProgram({
            appId: '',
            path: 'page/index/index?id=123',
            extraData: {
                foo: 'bar'
            },
            envVersion: 'trial',
            success(res) {
                // 打开成功
            }
        })
    },
    handleOrderPrint() {
        let _this = this
        let isConnBLE = app.globalData.isConnBLE
        if (isConnBLE) {
            // setTimeout(this.printTheOrder, 5000)
            _this.printTheOrder()
        } else {
            app.globalData.currentPageJs = this
            print.preparePrint()
        }
    },
    // 打印配货单
    printTheOrder() {
        let that = this;
        let canvasWidth = that.data.canvasWidth
        let canvasHeight = that.data.canvasHeight
        let brandName = app.globalData.brandInfo.brandName
        let order = this.data.order
        let details = this.data.details
        let dynamicCargoData = this.data.dynamicCargoData
        let customerBillStat = this.data.customerBillStat
        let orderNo = order.orderNo
        let orderTime = order.orderTime
        let remark = order.remark ? order.remark : ""
        let receiver = order.receiver ? order.receiver : ""
        let rphone = order.rphone ? order.rphone : ""
        let rarea = order.rarea ? order.rarea : ""
        let raddress = order.raddress ? order.raddress : ""
        let amount = order.amount ? order.amount : 0
        let settleAmount = order.settleAmount ? order.settleAmount : 0
        let qty = order.qty ? order.qty : 0
        let unSettleAmount = amount - settleAmount
        let totalUnSettleAmount = customerBillStat && customerBillStat != null && customerBillStat.unSettleAmount ? customerBillStat.unSettleAmount : 0
        let command = esc.jpPrinter.createNew()
        let time = util.formatTime(new Date());

        //58mm 纸张
        let offset_col_2 = 138;
        let offset_col_3 = 228;
        let offset_col_4 = 310;
        let divide = "--------------------------------"

        //80mm 纸张
        // let offset_col_2 = 200;
        // let offset_col_3 = 350;
        // let offset_col_4 = 495;
        // let divide = "----------------------------------------------"


        command.init() //初始化打印机

        command.setSelectJustification(1) //居中
        command.setCharacterSize(9); //设置倍高倍宽
        command.setText(brandName);
        command.setPrint(); //打印并换行

        command.setSelectJustification(1) //居中
        command.setCharacterSize(9); //设置倍高倍宽
        command.setText("销售单");
        command.setPrint(); //打印并换行
        command.setPrint();

        command.setCharacterSize(8); //设置倍高倍宽
        command.setSelectJustification(0) //设置居左
        command.setText("客户：" + receiver);
        command.setPrint(); //打印并换行

        command.setCharacterSize(8); //设置倍高倍宽
        command.setSelectJustification(0) //设置居左
        command.setText("联系方式：" + rphone);
        command.setPrint(); //打印并换行

        command.setCharacterSize(8); //设置倍高倍宽
        command.setSelectJustification(0) //设置居左
        command.setText("送货地址：" + rarea + " " + raddress);
        command.setPrint(); //打印并换行

        command.setCharacterSize(8); //设置倍高倍宽
        command.setSelectJustification(0) //设置居左
        command.setText("单号：" + orderNo);
        command.setPrint(); //打印并换行

        command.setCharacterSize(8); //设置倍高倍宽
        command.setSelectJustification(0) //设置居左
        command.setText("业务日期：" + orderTime);
        command.setPrint(); //打印并换行

        command.setCharacterSize(8); //设置倍高倍宽
        command.setSelectJustification(0) //设置居左
        command.setText(divide);
        command.setPrint(); //打印并换行

        command.setSelectJustification(0)
        command.setCharacterSize(8); //设置倍高倍宽
        command.setText("商品")
        command.setAbsolutePrintPosition(offset_col_2)
        command.setText("数量");
        command.setAbsolutePrintPosition(offset_col_3)
        command.setText("单价");
        command.setAbsolutePrintPosition(offset_col_4)
        command.setText("金额");
        command.setPrint()

        for (let i = 0; i < dynamicCargoData.length; i++) {
            let cargoObj = dynamicCargoData[i]
            let cargoNo = cargoObj.cargoNo
            let cargoName = cargoObj.cargoName ? cargoObj.cargoName : ""

            command.setSelectJustification(0)
            command.setCharacterSize(8); //设置倍高倍宽
            command.setText(cargoNo + "/" + cargoName)
            command.setPrint()

            let skuInfoList = cargoObj.skuInfoList
            for (let j = 0; j < skuInfoList.length; j++) {
                let skuInfo = skuInfoList[j]
                command.setSelectJustification(0)
                command.setCharacterSize(8); //设置倍高倍宽
                command.setAbsolutePrintPosition(15)
                command.setText(skuInfo.color + " " + skuInfo.size)
                command.setAbsolutePrintPosition(offset_col_2)
                command.setText(skuInfo.qty);
                command.setAbsolutePrintPosition(offset_col_3)
                command.setText(skuInfo.price);
                command.setAbsolutePrintPosition(offset_col_4)
                command.setText(skuInfo.amount);
                command.setPrint()
            }
        }

        command.setCharacterSize(8); //设置倍高倍宽
        command.setSelectJustification(0) //设置居左
        command.setText(divide);
        command.setPrint(); //打印并换行

        // command.setSelectJustification(0)
        // command.setCharacterSize(8); //设置倍高倍宽
        // command.setAbsolutePrintPosition(0)
        // command.setText("合计")
        // command.setAbsolutePrintPosition(offset_col_2)
        // command.setText(qty);
        // command.setAbsolutePrintPosition(offset_col_4)
        // command.setText("￥" + amount);
        // command.setPrint()

        // command.setCharacterSize(8); //设置倍高倍宽
        // command.setSelectJustification(0) //设置居左
        // command.setText(divide);
        // command.setPrint(); //打印并换行

        // command.setSelectJustification(0)
        // command.setCharacterSize(8); //设置倍高倍宽
        // command.setRelativePrintPositon(0)
        // command.setText("实收金额:￥" + settleAmount)
        // command.setPrint()
        //
        // command.setCharacterSize(8); //设置倍高倍宽
        // command.setSelectJustification(0) //设置居左
        // command.setText(divide);
        // command.setPrint(); //打印并换行
        //
        // command.setSelectJustification(0)
        // command.setCharacterSize(8); //设置倍高倍宽
        // command.setRelativePrintPositon(0)
        // command.setText("本单欠款:￥" + unSettleAmount + "  总欠款:￥" + totalUnSettleAmount)
        // command.setPrint()

        // command.setCharacterSize(8); //设置倍高倍宽
        // command.setSelectJustification(0) //设置居左
        // command.setText(divide);
        // command.setPrint(); //打印并换行

        command.setCharacterSize(8); //设置倍高倍宽
        command.setSelectJustification(0) //设置居左
        command.setText("备注：" + remark);
        command.setPrint(); //打印并换行
        command.setPrint(); //打印并换行

        command.setCharacterSize(8); //设置倍高倍宽
        command.setSelectJustification(0) //设置居左
        command.setText("打印时间：" + time);
        command.setPrint(); //打印并换行

        // command.setText("扫码下方二维码进行付款:")
        // command.setPrint()
        // command.setSelectSizeOfModuleForQRCode(5)
        // command.setSelectErrorCorrectionLevelForQRCode(49)
        // command.setStoreQRCodeData("http://img.matforever.cn/image/FKAJ98126530")
        // command.setPrintQRCode()

        command.setPrint()
        command.setPrint()
        command.setPrint()
        command.setPrint()
        command.setPrint()
        //切纸
        command.setCutter()
        this.prepareSend(command.getData()) //准备发送数据
    },
    prepareSend: function (buff) { //准备发送，根据每次发送字节数来处理分包数量
        // console.log(buff)
        var that = this
        var time = that.data.oneTimeData
        var looptime = parseInt(buff.length / time);
        var lastData = parseInt(buff.length % time);
        // console.log(looptime + "---" + lastData)
        that.setData({
            looptime: looptime + 1,
            lastData: lastData,
            currentTime: 1,
        })
        that.Send(buff)
    },

    Send: function (buff) { //分包发送
        var that = this
        var currentTime = that.data.currentTime
        var loopTime = that.data.looptime
        var lastData = that.data.lastData
        var onTimeData = that.data.oneTimeData
        var printNum = that.data.printerNum
        var currentPrint = that.data.currentPrint
        var buf
        var dataView
        if (currentTime < loopTime) {
            buf = new ArrayBuffer(onTimeData)
            dataView = new DataView(buf)
            for (var i = 0; i < onTimeData; ++i) {
                dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
            }
        } else {
            buf = new ArrayBuffer(lastData)
            dataView = new DataView(buf)
            for (var i = 0; i < lastData; ++i) {
                dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
            }
        }
        // console.log("第" + currentTime + "次发送数据大小为：" + buf.byteLength)
        wx.writeBLECharacteristicValue({
            deviceId: app.BLEInformation.deviceId,
            serviceId: app.BLEInformation.writeServiceId,
            characteristicId: app.BLEInformation.writeCharaterId,
            value: buf,
            success: function (res) {
                console.log("success: %o", res)
                if (currentTime <= loopTime) {
                    // wx.showLoading({
                    //   title: '传输中...',
                    // })
                } else {
                    wx.showToast({
                        title: '已打印第' + currentPrint + '张成功',
                    })
                }
            },
            fail: function (e) {
                console.log(e)
                that.orderPrintStatusUpdate(2)
                wx.showToast({
                    title: '打印第' + currentPrint + '张失败',
                    icon: 'none',
                })
            },
            complete: function () {
                currentTime++
                if (currentTime <= loopTime) {
                    that.setData({
                        currentTime: currentTime
                    })
                    that.Send(buff)
                } else {
                    if (currentPrint == printNum) {
                        that.setData({
                            looptime: 0,
                            lastData: 0,
                            currentTime: 1,
                            isReceiptSend: false,
                            currentPrint: 1
                        })
                        that.orderPrintStatusUpdate(1)
                    } else {
                        currentPrint++
                        that.setData({
                            currentPrint: currentPrint,
                            currentTime: 1,
                        })
                        that.Send(buff)
                    }
                }
            }
        })
    },

})
